<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 一行 -->
      <el-row>
        <!-- 一列 -->
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- :class="['bdbottom']" 动态绑定每一个标签，使得每一个标签下面有一条线 -->
            <!-- 同时还需要给第一个标签头部加一条线，故通过索引判断，i1===0?'datop':'',如果等于0，就加 -->
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限  span=5，占了5列-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限  span=19，占了19列-->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <!-- 行 -->
                <!-- 给每一行头部加一条线，第一标签不需要 -->
                <el-row
                  :class="[i2===0? '':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 这一列 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 这一列 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- 放置作用域插槽 -->
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户弹窗区域 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="30%">
      <el-form :rules="addFormRules" ref="addRolesRef" :model="addRolesForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹窗区域 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%">
      <el-form :rules="addFormRules" ref="editRolesRef" :model="editForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" >
     <!-- 树形空间 data绑定数据，props绑定lable名字,和children绑定父子节点通过什么绑定 -->
     <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolelist: [],
      addRolesForm: {
        roleName: "",
        roleDesc: ""
      },
      editForm: {},
      // 所有权限的数据
      rightsList:[],
      //树形控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      //默认选中的节点，id值数组
      defKeys:[],
      //当前即将分配权限的角色id
      roleId:'',
      addDialogVisible: false,
      editDialogVisible: false,
      setRightsDialogVisible:false,
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "角色名的长度为2~10个字符之间",
            trigger: "blur"
          }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.rolelist = res.data;
      console.log(this.rolelist);
    },
    //添加用户
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addRolesForm);
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.addDialogVisible = false;
      this.getRolesList();
    },
    // 修改用户,获取用户信息
    async showRoles(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      //this.$message.success(res.meta.msg)
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    //修改用户信息提交
    async editRoles() {
      //根据showRoles()里面，this.editForm=res.data,将editForm里面的值传给后台，不清楚的可以打印一下
      const { data: res } = await this.$http.put(
        "roles/" + this.editForm.roleId,
        { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meat.msg);
      }
      this.$message.success("修改成功");
      this.editDialogVisible = false;
      this.getRolesList();
    },
    //删除用户请求
    deleteRoles(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete("roles/" + id).then(response => {
            if (response.data.meta.status !== 200) {
              return this.$message.error(response.data.meta.msg);
            }
            this.$message.success(response.data.meta.msg);
            this.getRolesList();
          });
          //   const {data:res} = this.$http.delete("roles/"+id)
          //   if(res.meta.success !== 200){
          //       return this.$message.error(res.meta.msg)
          //   }
          //   this.$message.success(res.data.msg)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //对应id删除相应的权限标签
    removeRightById(role, rightId) {
      //弹框提示用户是否删除
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http
            .delete(`roles/${role.id}/rights/${rightId}`)
            .then(response => {
              if (response.data.meta.status !== 200) {
                return this.$message.error(response.data.meta.msg);
              }
              this.$message.success(response.data.meta.msg);
              // this.getRolesList();
              //将删除后的返回值重新赋值给role.childre，当前角色的childre属性，就可以达到不用刷新整个列表，点击删除，显示最新数据
              role.children = response.data.data;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //展示分配权限的对话框
    async showSetRightsDialog(role) {
      //将这个id放置在data中，后面修改分配权限需要使用
      this.roleId=role.id
      // 获取所有权限的数据
      const {data:res} = await this.$http.get("rights/tree")
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      //把获取到的权限数据保存到data中
      this.rightsList = res.data
      // console.log(this.rightsList)
      //递归获取三级节点的id
      this.defKeys=[]
      this.getLeafKeys(role,this.defKeys)
      this.setRightsDialogVisible=true
    },
    //定义一个递归函数，用来获取角色所拥有的三级权限ID，并保存到defKeys数组中
    getLeafKeys(node,arr){
      //判断该节点是否是三级节点,如果没有子节点则为三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item,arr)
      });
    },
    //点击确定为用户分配权限
    async allotRights(){
      const keys = [
        //返回被选中的节点，其中...是展开运算符
        ...this.$refs.treeRef.getCheckedKeys(),
        //返回半选中的节点
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      //以逗号拼接数据
      const idStr = keys.join(',')
      // console.log(idStr)
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
      if(res.meta.status !==200){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightsDialogVisible=false
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
// 纵向上居中
.vcenter {
  display: flex;
  align-items: center;
}
</style> 